import React, { useState } from 'react'
import Heros from '../../pages/Heros/Heros'
import axios from 'axios'
import { useEffect } from 'react'
import './Heroslist.css'
import PubSub from 'pubsub-js'
import { Link,useNavigate, useSearchParams} from 'react-router-dom'

export default function Heroslist() {
    //创建状态
    let [heros,setHeros]=useState([]);
    let [likename,setLikename] = useState("");

    //  编程式导航
    let navigate = useNavigate();

    //单独模拟 componentDidMount
    useEffect(()=>{
        //订阅消息
        PubSub.subscribe("keyword",(msg,data)=>{
            console.log("这是订阅信息",msg,data);
            //更新状态
            setLikename(data);
        });

        async function main(){
           let result = await axios.get(`http://api.xiaohigh.com/heros?name_like=${likename}`);
        //    console.log(result.data);
           //设置数据
           setHeros(result.data);
        }

        //入口
        main();

        return ()=>{  // 模拟  componentWillUnmount 
            // console.log("componentWillUnmount");
            PubSub.unsubscribe("keyword");
        }

    },[likename])

    //点击事件demo导航
    let demo=(id,name)=>{
        return ()=>{
            //复杂的逻辑运算 或者判断
            // 1. 模拟 useParams();  必须修改路由配置  动态路由
            // navigate(`/heroscon/${id}/${name}`);

            // 2. 模拟 useSearchParams();   必须修改路由配置  静态路由
            // navigate(`/heroscon?id=${id}&name=${name}`);

            // 3. 模拟 useLocation()   必须修改路由配置  静态路由
            navigate("/heroscon",{
                state:{
                    id,
                    name
                }
            });
        }
    }

  return (
    <div className='heroslist'>
            <h1>英雄列表</h1>
            <hr />
            <ul>
                {
                    heros.map((item)=>{
                        return (
                            <li key={item.id}>
                                {/* <Link to={`/heroscon/${item.id}/${item.name}`}> */}
                                {/* <Link to={`/heroscon?id=${item.id}&name=${item.name}`}> */}
                                {/* <Link to="/heroscon" state={{id:item.id,name:item.name}}> */}
                                <img onClick={demo(item.id,item.name)} src={`https://cdn.xiaohigh.com${item.image}`} alt="" />
                                {/* </Link> */}
                                <h3>{item.name}</h3>
                            </li>
                        )
                    })
                }
                
                {
                    heros.length === 0 ? <p>暂无数据</p> : ""
                }

            </ul>



        </div>
  )
}
